<!DOCTYPE html>
<html lang="en"><head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1"><!-- Begin Jekyll SEO tag v2.8.0 -->
<title>0008: Callbacks and Events | gtkDcoding</title>
<meta name="generator" content="Jekyll v4.3.4" />
<meta property="og:title" content="0008: Callbacks and Events" />
<meta name="author" content="Ron Tarrant" />
<meta property="og:locale" content="en_US" />
<meta name="description" content="How GTK Buttons handle signals and events - a D language tutorial." />
<meta property="og:description" content="How GTK Buttons handle signals and events - a D language tutorial." />
<link rel="canonical" href="http://localhost:4000/posts/0008-callbacks.html" />
<meta property="og:url" content="http://localhost:4000/posts/0008-callbacks.html" />
<meta property="og:site_name" content="gtkDcoding" />
<meta property="og:type" content="article" />
<meta property="article:published_time" content="2019-02-08T00:00:00-05:00" />
<meta name="twitter:card" content="summary" />
<meta property="twitter:title" content="0008: Callbacks and Events" />
<script type="application/ld+json">
{"@context":"https://schema.org","@type":"BlogPosting","author":{"@type":"Person","name":"Ron Tarrant"},"dateModified":"2019-02-08T00:00:00-05:00","datePublished":"2019-02-08T00:00:00-05:00","description":"How GTK Buttons handle signals and events - a D language tutorial.","headline":"0008: Callbacks and Events","mainEntityOfPage":{"@type":"WebPage","@id":"http://localhost:4000/posts/0008-callbacks.html"},"url":"http://localhost:4000/posts/0008-callbacks.html"}</script>
<!-- End Jekyll SEO tag -->
<link rel="stylesheet" href="../assets/main.css">
  <link rel="stylesheet" href="../css/style.css" /><link type="application/atom+xml" rel="alternate" href="http://localhost:4000/feed.xml" title="gtkDcoding" /></head>
<body><header class="site-header" role="banner">

  <div class="wrapper"><a class="site-title" rel="author" href="../">gtkDcoding</a><nav class="site-nav">
        <input type="checkbox" id="nav-trigger" class="nav-trigger" />
        <label for="nav-trigger">
          <span class="menu-icon">
            <svg viewBox="0 0 18 15" width="18px" height="15px">
              <path d="M18,1.484c0,0.82-0.665,1.484-1.484,1.484H1.484C0.665,2.969,0,2.304,0,1.484l0,0C0,0.665,0.665,0,1.484,0 h15.032C17.335,0,18,0.665,18,1.484L18,1.484z M18,7.516C18,8.335,17.335,9,16.516,9H1.484C0.665,9,0,8.335,0,7.516l0,0 c0-0.82,0.665-1.484,1.484-1.484h15.032C17.335,6.031,18,6.696,18,7.516L18,7.516z M18,13.516C18,14.335,17.335,15,16.516,15H1.484 C0.665,15,0,14.335,0,13.516l0,0c0-0.82,0.665-1.483,1.484-1.483h15.032C17.335,12.031,18,12.695,18,13.516L18,13.516z"/>
            </svg>
          </span>
        </label>

        <div class="trigger"><a class="page-link" href="../about.html">About</a><a class="page-link" href="../index-reverse.html">Posts in Date Order</a><a class="page-link" href="../topics.html">Blog Posts by Topic</a></div>
      </nav></div>
</header>
<main class="page-content" aria-label="Content">
      <div class="wrapper">
        <article class="post h-entry" itemscope itemtype="http://schema.org/BlogPosting">
	<header class="post-header">
		<link rel="stylesheet" href="../css/font_size.css" />
		<link rel="stylesheet" href="../css/figure.css" />
		<link rel="stylesheet" href="../css/topics/button.css" />  <!-- sub in the tag/topic -->
		<link rel="stylesheet" href="../css/modal.css" />
		<link rel="stylesheet" href="../css/post.css" />
		<link rel="stylesheet" href="../css/mascot_effects.css" />

		
		
		<p class="post-meta">
		<time class="dt-published" datetime="2019-02-08T00:00:00-05:00" itemprop="datePublished">Friday, February 8, 2019
		</time>• by <span itemprop="author" itemscope itemtype="http://schema.org/Person"><span class="p-author h-card" itemprop="name">Ron Tarrant</span></span></p>
	</header>

	<div class="post-content e-content" itemprop="articleBody">
		<div class="skew-line"></div>
		<h1 id="0008-callbacks-and-events">0008: Callbacks and Events</h1>

<p>In this blog entry, we’ll be looking at two flavours of callback and the implications of using each one.</p>

<p><em>GtkD</em> signals fall into two broad categories:</p>

<ul>
  <li>those that expect association with void callbacks, and</li>
  <li>those that expect callbacks to return a value, usually a Boolean.</li>
</ul>

<p>So, what’s the difference?</p>

<h3 id="void-callbacks">void Callbacks</h3>

<div class="screenshot-frame">
	<div class="frame-header">
		Results of this example:
	</div>
	<div class="frame-screenshot">
		<figure>
			<img id="img0" src="../images/screenshots/002_button/button_06.png" alt="Current example output" />
			
			<!-- Modal for screenshot -->
			<div id="modal0" class="modal">
				<span class="close">&times;</span>
				<img class="modal-content" id="img00" />
				<div id="caption"></div>
			</div>
			
			<script>
			// Get the modal
			var modal = document.getElementById("modal0");
			
			// Get the image and insert it inside the modal - use its "alt" text as a caption
			var img = document.getElementById("img0");
			var modalImg = document.getElementById("img00");
			var captionText = document.getElementById("caption");

			img.onclick = function()
			{
			  modal.style.display = "block";
			  modalImg.src = this.src;
			  captionText.innerHTML = this.alt;
			}
			
			// Get the <span> element that closes the modal
			var span = document.getElementsByClassName("close")[0];
			
			// When the user clicks on <span> (x), close the modal
			span.onclick = function()
			{ 
				modal.style.display = "none";
			}
			</script>
			<figcaption>
			Current example output
			</figcaption>
		</figure>
	</div>

	<div class="frame-terminal">
		<figure class="right">
			<img id="img1" src="../images/screenshots/002_button/button_06_term.png" alt="Current example terminal output" />

			<!-- Modal for terminal shot -->
			<div id="modal1" class="modal">
				<span class="close1">&times;</span>
				<img class="modal-content" id="img11" />
				<div id="caption"></div>
			</div>
			
			<script>
			// Get the modal
			var modal = document.getElementById("modal1");
			
			// Get the image and insert it inside the modal - use its "alt" text as a caption
			var img = document.getElementById("img1");
			var modalImg = document.getElementById("img11");
			var captionText = document.getElementById("caption");

			img.onclick = function()
			{
			  modal.style.display = "block";
			  modalImg.src = this.src;
			  captionText.innerHTML = this.alt;
			}
			
			// Get the <span> element that closes the modal
			var span = document.getElementsByClassName("close1")[0];
			
			// When the user clicks on <span> (x), close the modal
			span.onclick = function()
			{ 
				modal.style.display = "none";
			}
			</script>

			<figcaption>
				Current example terminal output (click for enlarged view)
			</figcaption>
		</figure>
	</div>

	<div class="frame-footer">
		The code file for this example is available <a href="https://github.com/rontarrant/gtkd_demos/blob/master/002_button/button_06_void_callback.d" target="_blank">here</a>.
	</div>
</div>

<p>The most noticeable feature of a void callback is that it isn’t processed as a <em>GDK Event</em>. if you have a look at the definition of a void-return callback, you’ll see one argument of type <em>Button</em>.</p>

<div class="language-d highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kt">void</span> <span class="n">callbackName</span><span class="p">(</span><span class="n">Button</span> <span class="n">b</span><span class="p">)</span>
<span class="p">{</span>
      <span class="p">...</span>
<span class="p">}</span>
</code></pre></div></div>

<p>No mention of an <code class="language-plaintext highlighter-rouge">Event</code>, no return value. Clearly, this is a quick-n-dirty approach meant to avoid extra baggage and detail. Hook the button up to the signal, do a straight jump into the callback function, do your business and get out with no data returned to the caller. And don’t forget that class methods can have access to any data stored at the top level of the class/object, so this approach doesn’t hamper us.</p>

<p>And when we hook up the signal, it too is straightforward and simple:</p>

<div class="language-d highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">addOnClicked</span><span class="p">(&amp;</span><span class="n">callbackName</span><span class="p">);</span>
</code></pre></div></div>

<h3 id="bool-callbacks">bool Callbacks</h3>

<div class="screenshot-frame">
	<div class="frame-header">
		Results of this example:
	</div>
	<div class="frame-screenshot">
		<figure>
			<img id="img2" src="../images/screenshots/002_button/button_07.png" alt="Current example output" />								<!-- img# -->
			
			<!-- Modal for screenshot -->
			<div id="modal2" class="modal">																								<!-- modal# -->
				<span class="close2">&times;</span>																					<!-- close# -->
				<img class="modal-content" id="img22" />																					<!-- img## -->
				<div id="caption"></div>
			</div>
			
			<script>
			// Get the modal
			var modal = document.getElementById("modal2");																			// modal#
			
			// Get the image and insert it inside the modal - use its "alt" text as a caption
			var img = document.getElementById("img2");																				// img#
			var modalImg = document.getElementById("img22");																		// img##
			var captionText = document.getElementById("caption");

			img.onclick = function()
			{
			  modal.style.display = "block";
			  modalImg.src = this.src;
			  captionText.innerHTML = this.alt;
			}
			
			// Get the <span> element that closes the modal
			var span = document.getElementsByClassName("close2")[0];															// close#
			
			// When the user clicks on <span> (x), close the modal
			span.onclick = function()
			{ 
				modal.style.display = "none";
			}
			</script>
			<figcaption>
			Current example output
			</figcaption>
		</figure>
	</div>

	<div class="frame-terminal">
		<figure class="right">
			<img id="img3" src="../images/screenshots/002_button/button_07_term.png" alt="Current example terminal output" /> 							<!-- img#, filename -->

			<!-- Modal for terminal shot -->
			<div id="modal3" class="modal">																												<!-- modal# -->
				<span class="close3">&times;</span>																										<!-- close# -->
				<img class="modal-content" id="img33" />																									<!-- img## -->
				<div id="caption"></div>
			</div>
			
			<script>
			// Get the modal
			var modal = document.getElementById("modal3");																							// modal#
			
			// Get the image and insert it inside the modal - use its "alt" text as a caption
			var img = document.getElementById("img3");																								// img#
			var modalImg = document.getElementById("img33");																						// img##
			var captionText = document.getElementById("caption");

			img.onclick = function()
			{
			  modal.style.display = "block";
			  modalImg.src = this.src;
			  captionText.innerHTML = this.alt;
			}
			
			// Get the <span> element that closes the modal
			var span = document.getElementsByClassName("close3")[0];																				// close#
			
			// When the user clicks on <span> (x), close the modal
			span.onclick = function()
			{ 
				modal.style.display = "none";
			}
			</script>

			<figcaption>
				Current example terminal output (click for enlarged view)
			</figcaption>
		</figure>
	</div>

	<div class="frame-footer">																																<!-- filename (below)-->
		The code file for this example is available <a href="https://github.com/rontarrant/gtkd_demos/blob/master/002_button/button_07_bool_callback.d" target="_blank">here</a>.
	</div>
</div>

<p>Bool-return callbacks are more complex. For one thing, they’re processed as <em>GDK</em> <code class="language-plaintext highlighter-rouge">Events</code>. <code class="language-plaintext highlighter-rouge">Events</code> can originate from anything controlled by the user via keyboard, mouse, or any other input device. <code class="language-plaintext highlighter-rouge">Events</code> are triggered by:</p>

<ul>
  <li>the motion of the mouse pointer,</li>
  <li>the pressing of a key,</li>
  <li>a combination of keys, or</li>
  <li>the visibility of a UI entity.</li>
</ul>

<p><code class="language-plaintext highlighter-rouge">Events</code> can be chained together by hooking up multiple signals to the same widget (usually a <code class="language-plaintext highlighter-rouge">Button</code>) – something we’ll talk more about later.</p>

<p>In a nutshell, hooking up a <code class="language-plaintext highlighter-rouge">bool</code> signal passes an <code class="language-plaintext highlighter-rouge">Event</code> structure into our callback method. From that <code class="language-plaintext highlighter-rouge">Event</code> we can pull any pertinent data we might want to work with such as the position of the mouse, which qualifier key(s) were used, or the state of a widget.</p>

<h4 id="why-a-boolean-return-value-is-of-value">Why a Boolean Return Value is of… Value</h4>

<p>Another feature of <em>GDK</em> signals is that they can be chained together. Hook up any number of signals, or two or more instances of the same signal, and you’ve got a chain of signals. If you want, this signal chain can be interrupted by changing the return value of one of the callbacks.</p>

<p>So, let’s say you’ve got three signals hooked up:</p>

<div class="language-d highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">addOnButtonRelease</span><span class="p">(&amp;</span><span class="n">callbackOne</span><span class="p">);</span>
<span class="n">addOnButtonRelease</span><span class="p">(&amp;</span><span class="n">callbackTwo</span><span class="p">);</span>
<span class="n">addOnButtonRelease</span><span class="p">(&amp;</span><span class="n">callbackThree</span><span class="p">);</span>
</code></pre></div></div>

<p>And let’s say that some other part of our code can switch <code class="language-plaintext highlighter-rouge">callbackTwo()</code>’s return value between <code class="language-plaintext highlighter-rouge">true</code> and <code class="language-plaintext highlighter-rouge">false</code>. When it returns <code class="language-plaintext highlighter-rouge">true</code>, only <code class="language-plaintext highlighter-rouge">callbackOne()</code> and <code class="language-plaintext highlighter-rouge">callbackTwo()</code> are called. But when it’s switched to <code class="language-plaintext highlighter-rouge">false</code>, <code class="language-plaintext highlighter-rouge">callbackThree()</code> also gets called.</p>

<p>When you hook up multiple signals, they’re processed in the same order as they’re hooked up.</p>

<p>So in short:</p>

<ul>
  <li><code class="language-plaintext highlighter-rouge">return(true)</code>: stop processing callbacks and return to the main loop, and</li>
  <li><code class="language-plaintext highlighter-rouge">return(false)</code>: more callbacks to come, keep going.</li>
</ul>

<h3 id="why-these-differences-matter">Why These Differences Matter</h3>

<p>As I said, a <code class="language-plaintext highlighter-rouge">void</code> callback is for quick-n-dirty handling of user input. When you need to get fancy, deal with the details of the event that triggered the callback or deal with an interruptible callback chain, you need to use one of the Boolean-oriented signals.</p>

<h3 id="to-the-code">To the Code…</h3>

<p>Comparing today’s example files, you won’t see much difference until you get to the <code class="language-plaintext highlighter-rouge">MyButton</code> class. (For now, ignore the fact that I’ve set up the <code class="language-plaintext highlighter-rouge">TestRigWindow</code>’s <code class="language-plaintext highlighter-rouge">onDestroy</code> signal in two quite different ways, which in the end give us exactly the same functionality.) No, what we’re interested in is the signal hook-ups in the <code class="language-plaintext highlighter-rouge">MyButton</code> and <code class="language-plaintext highlighter-rouge">MyArgsButton</code> classes.</p>

<h4 id="void-ness">void-ness</h4>

<p>Here, have a look:</p>

<div class="language-d highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">addOnClicked</span><span class="p">(</span><span class="k">delegate</span> <span class="kt">void</span><span class="p">(</span><span class="n">_</span><span class="p">)</span> <span class="p">{</span> <span class="n">buttonAction</span><span class="p">(</span><span class="n">args</span><span class="p">);</span> <span class="p">});</span>
</code></pre></div></div>

<p>The call to <em><code class="language-plaintext highlighter-rouge">addOnClicked()</code></em> may seem like overkill, but here’s how it breaks down:</p>

<ul>
  <li>Because we want to pass the command line arguments all the way into the <code class="language-plaintext highlighter-rouge">MyButton</code> object, we have to define this callback as a delegate. If we didn’t, we’d get a compiler error.</li>
  <li><code class="language-plaintext highlighter-rouge">void(_)</code> defines the callback’s return value and that underscore basically says: the widget calling this callback is the widget we’re talking about. This may seem unnecessary, but when you consider that ‘delegate’ is about forcing a callback to remain within the scope of the caller, it makes more sense. It’s a way of making sure the scope of caller/callback are in sync.</li>
  <li>The curly braces surround what is, in effect, a list of statements in an inline function. Because the callback function itself is here reduced to just another statement in an ersatz function, we can get away with passing those arguments right in there.</li>
</ul>

<p>And there you have it. If we weren’t passing in the command line arguments, you wouldn’t need such a complex callback definition. Instead, you could use what we’ve used before, a simple:</p>

<div class="language-d highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">addOnClicked</span><span class="p">(&amp;</span><span class="n">callbackFunction</span><span class="p">);</span>
</code></pre></div></div>

<h4 id="bool-ness">bool-ness</h4>

<p>Looking at the <code class="language-plaintext highlighter-rouge">bool</code> callback example, the only thing about the signal hook-up that’s different is what appears directly after the <code class="language-plaintext highlighter-rouge">delegate</code> keyword:</p>

<div class="language-d highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">addOnButtonRelease</span><span class="p">(</span><span class="k">delegate</span> <span class="kt">bool</span><span class="p">(</span><span class="n">Event</span> <span class="n">e</span><span class="p">,</span> <span class="n">Widget</span> <span class="n">w</span><span class="p">){</span> <span class="n">buttonAction</span><span class="p">(</span><span class="n">args</span><span class="p">);</span> <span class="k">return</span><span class="p">(</span><span class="kc">false</span><span class="p">);</span> <span class="p">}</span> <span class="p">);</span>
</code></pre></div></div>

<p>Again, the first bit is the return value we’re expecting from the callback function followed by the invisible arguments being passed into the callback function.</p>

<p><strong>Invisible arguments?</strong></p>

<p>Yeah, I didn’t mention it before, but if you look at either example, the arguments immediately following delegate void or delegate <code class="language-plaintext highlighter-rouge">bool</code> aren’t mentioned in the actual callback functions. It seems that because they’re self-referential, they don’t need to be mentioned, not the <code class="language-plaintext highlighter-rouge">Button</code>, not the <code class="language-plaintext highlighter-rouge">Widget</code>, and not the <code class="language-plaintext highlighter-rouge">Event</code>. The only argument we mention in the callback function is the string array containing the command line arguments.</p>

<h3 id="conclusion">Conclusion</h3>

<p>Further down the road, we’ll revisit callbacks. There’s lots more to talk about: signal chains, interrupting signal chains… yeah, all kinds of stuff.</p>

<p>But for now, you know the basics and you have two new techniques for hooking up signals. Until next time, happy D-coding and may the widgets do wonders to your head-space.</p>

<div class="blog-nav">
	<div style="float: left;">
		<a href="./0007-button-release-and-reorganizing-the-code.html">Previous: Button Release</a>
	</div>
	<div style="float: right;">
		<a href="./0009-boxes.html">Next: Boxes</a>
	</div>
</div>

<p>
	<h3></h3>
<div class="inpage-frame">
	<a href="https://github.com/sponsors/rontarrant">
		<BR>
		<BR>
		<B>Is this article useful? Educational? Entertaining, perhaps?</B>
		<BR>
		<figure class="left">
			<img src="../images/favorite_32.png" alt="Sponsorship heart" style="width: 32px; height: 32px;">
		</figure>
		You're free to accept or decline this invitation to become our newest sponsor.
	</a>
</div>
	<h4 class="comment-blurb"><B>Comments? Questions? Observations?</B></h4>
	<p>
		Did we miss a tidbit of information that would make this post even more informative? Let's talk about it in the comments.
	</p>
	<script src="https://utteranc.es/client.js"
		repo="rontarrant"
		issue-term="pathname"
		theme="github-light"
		crossorigin="anonymous"
		async>
	</script>
	<ul>
		<li> come on over to the <a href="https://forum.dlang.org/">D Language Forum</a> and look for one of the <i>gtkDcoding</i> announcement posts, </li>
		<li> drop by <a href="https://forum.gtkd.org/">the <i>GtkD Forum</i></a>,</li>
		<li> follow the link below to email me, or</li>
		<li> go to the	<a href="https://www.facebook.com">gtkDcoding Facebook page.</a></li>
	</ul>
</p>
<p> You can also subscribe <a href="/feed.xml">via RSS</a> so you won't miss anything. Thank you very much for dropping by.</p>
<p>&copy; Copyright 2025 Ron Tarrant </p>
</div>

	<a class="u-url" href="./0008-callbacks.html" hidden></a>
</article>

      </div>
    </main><footer class="site-footer h-card">
  <data class="u-url" href="/"></data>

  <div class="wrapper">

    <h2 class="footer-heading">gtkDcoding</h2>

    <div class="footer-col-wrapper">
      <div class="footer-col footer-col-1">
        <ul class="contact-list">
          <li class="p-name">Ron Tarrant</li><li><a class="u-email" href="mailto:gtkDcoding@gmail.com">gtkDcoding@gmail.com</a></li></ul>
      </div>

      <div class="footer-col footer-col-2"><ul class="social-media-list"><li><a href="https://github.com/rontarrant"><svg class="svg-icon"><use xlink:href="../assets/minima-social-icons.svg#github"></use></svg> <span class="username">rontarrant</span></a></li></ul>
</div>

      <div class="footer-col footer-col-3">
        <p>Simple examples of how to use GtkD to build GUI applications.</p>
      </div>
    </div>

  </div>

</footer>
</body>

</html>
